package builder;

import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.Set;

import builder.trainer.Trainer;
import builder.trainer.data.DataManager;
import builder.tree.DecisionNode;
import builder.tree.Node;

public class Builder {
	
	public static void main(String[] args){
		String file = "C:/Users/wminglia/Documents/Workspaces/Course Projects/wml.is.decisiontree/data.txt";
		DataManager dataManager = new DataManager(file);// records in order
		int objColumn = 6;
		ArrayList<Node> nodes = Builder.buildTree(dataManager, objColumn );
		Builder.printTree(nodes);
		
		
	}
	
	public static ArrayList<Node> buildTree(DataManager dm, int objColumn) {
		Trainer trainer = new Trainer();
		ArrayList<Node> nodes = trainer.train(dm, objColumn);
		Builder.buildTree(nodes);
		return nodes;
	}

	public static void printTree(ArrayList<Node> nodes) {
		for (Node node : nodes) {
			for (int i = 0; i < node.getLevel(); i++)
				System.out.print("\t");
			if (node instanceof DecisionNode) {
				DecisionNode hNode = (DecisionNode) node;
					printDecisionNode(hNode);
					continue;
			} else {
				System.out.println(node.getAttrName() + "=" + node.getValue());
			}
		}
	}

	private static void printDecisionNode(DecisionNode hNode) {
		System.out.print(hNode.getAttrName() + "=" + hNode.getValue()
				+ "  -->  ");
		Set<Entry<String, Double>> decisions = hNode.getHesitation().entrySet();
		for (Entry<String, Double> d : decisions) {
			System.out.print(d.getKey() + "(" + d.getValue() * 100 + "%) || ");
		}
		System.out.println();
	}

	public static Node buildTree(ArrayList<Node> nodes) {
		Node root = nodes.get(0);
		Node currentNode = root;
		for (int i = 1; i < nodes.size(); i++) {
			Node node = nodes.get(i);
			while (currentNode.getChildrenAttrName() == null
					|| !currentNode.getChildrenAttrName().equals(
							node.getAttrName())) {
				currentNode = currentNode.getParent();
			}
			currentNode.addChild(node);
			node.setParent(currentNode);
			currentNode = node;
		}
		return root;
	}
}
